package com.metacube.metaconnect.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessages;

import com.metacube.metaconnect.Service.UserInformationService;
import com.metacube.metaconnect.model.LoginForm;

public class LoginAction extends Action {
	/*
	 * check login credentials of user when user attempt login
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		if (form == null)
			response.sendRedirect("index.jsp");
		else {
			LoginForm loginform = (LoginForm) form;

			String email = loginform.getEmail();
			String password = loginform.getPassword();

			try {
				boolean result = new UserInformationService().login(email,
						password);
				if (result) {
					request.getSession().setAttribute("emailId", email);
					return mapping.findForward("success");
				} else {
					ActionMessages errorList = new ActionMessages();
					request.setAttribute("loginError", "Invalid");
					saveErrors(request, errorList);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return mapping.findForward("failure");

	}
}
